<template>
  <div class="app-container">
    <div v-show="!detailInfo.visible && !modifyDeliverInfo.visible && !purchOrderDetailInfo.visible">
      <!-- <div class="width100"> -->
      <!-- 条件栏 -->
      <div class="filter-wrapper">
        <new-page-filter
          v-model:query="filterInfo.query.queryMap"
          :query-more-json="true"
          :filter-list="filterInfo.searchList"
          :filter-btn="filterInfo.searchBtn"
          :clear-type="clearType"
          :slip-select-request="slipSelectRequest"
        >
        </new-page-filter>
      </div>
      <div class="filter-wrapper">
        <new-page-filter :filter-btn="filterInfo.btnList">
          <template v-slot:filter-excel>
            <el-button :disabled="groupFlag" @click="exportExcel()"
              >导出excel
            </el-button>
          </template>
          <template v-slot:filter-print>
            <el-button :disabled="groupFlag" @click="print()">打印 </el-button>
          </template>
        </new-page-filter>
        <div class="display-flex">
          <el-button @click="preferenceInfo.visible = true">偏好设置</el-button>
        </div>
      </div>
      <!-- 表格 -->

      <table-container
        :refresh="tableInfo.refresh"
        :init-curpage="tableInfo.initCurpage"
        v-model:data="tableInfo.data"
        :api="tableInfo.api"
        :tab-index="true"
        :checkBox="false"
        :query="filterInfo.query"
        :field-list="tableInfo.fieldList"
        :handle="tableInfo.handle"
        @sortChange="sortChange"
        @handleEvent="handleEvent"
        @pageInfo="pageInfo"
      >
        <template v-slot:col-orderNo="scope">
          <span class="slip-edit" @click="showDetail(scope.row)">{{
            scope.row.orderNo || '-'
          }}</span>
        </template>
        <template v-slot:col-purchNo="scope">
          <span v-if="scope.row.purchNo" class="slip-edit" @click="showPurchDetail(scope.row)">{{
            scope.row.purchNo
          }}</span>
          <span v-else>-</span>
        </template>
      </table-container>
    </div>
    <InvoiceDetail
      v-if="detailInfo.visible"
      :id="detailInfo.id"
      v-model:visible="detailInfo.visible"
      :type="detailInfo.type"
      @returnBack="getList"
    />
    <ModifyOrder
      v-if="modifyDeliverInfo.visible"
      v-model:visible="modifyDeliverInfo.visible"
      :title="modifyDeliverInfo.title"
      :deliver-id="modifyDeliverInfo.deliverId"
      :order-id="modifyDeliverInfo.orderId"
      :receive-all="modifyDeliverInfo.receiveAll"
      :isEstimated="modifyDeliverInfo.isEstimated"
      @returnModify="getList"
    ></ModifyOrder>
    <PurchOrderDetail
      v-if="purchOrderDetailInfo.visible"
      v-model:visible="purchOrderDetailInfo.visible"
      :orderId="purchOrderDetailInfo.orderId"
      @returnBack="getList"
    />
    <SetPreference
      v-if="preferenceInfo.visible"
      v-model:visible="preferenceInfo.visible"
      :search-list="filterInfo.searchList"
      :field-list="tableInfo.fieldList"
      :customize-user-v-o="filterInfo.query.customizeUserVO"
      @callback="setPreferenceCallback"
    />
    <advanced-search
      v-if="advancedSearchInfo.visible"
      v-model:visible="advancedSearchInfo.visible"
      :field-list="tableInfo.fieldList"
      v-model:form-data="advancedSearchInfo.data"
      @callback="advancedSearchCallback"
    />
    <page-dialog
      v-show="dialogInfo.visible"
      :title="dialogInfo.title"
      v-model:visible="dialogInfo.visible"
      :width="dialogInfo.width"
      :bt-loading="dialogInfo.btLoading"
      :bt-list="dialogInfo.btList"
    >
      <div class="asset-msg">
        <div class="asset-msg-label">
          <i class="el-icon-warning"></i>{{ dialogInfo.msg }}：
        </div>
        <el-radio-group v-model="dialogInfo.flag">
          <el-radio :label="true">当前页数据</el-radio>
          <el-radio :label="false">全部页数据</el-radio>
        </el-radio-group>
      </div>
    </page-dialog>
  </div>
</template>
<script setup name="pendDealDeliverOrder">
import SetPreference from '@/components/SetPreference/defaultSetPreference'
import PurchOrderDetail from "../../purch/order/detail"
import {
  getPendDealDeliverOrderCustomizeListPage,
  pendDealDeliverOrderExcelListDeliverOrder,
  pendDealDeliverOrderPrintDetailDeliverOrder,
} from '@/api/supplier.js'
import { getCustomizeSetting, updateUserCustomize } from '@/api/customize'
import { fatchTemplateByCode } from '@/api/base'
import { getSupplierAll } from '@/api/core'

const ModifyOrder = defineAsyncComponent(() =>
  import('@/views/stock/receiving/importModifyOrder')
)
const InvoiceDetail = defineAsyncComponent(() =>
  import('@/views/deliver/Invoice/detail')
)

const emits = defineEmits()
const { proxy } = getCurrentInstance()
const props = defineProps(['visible', 'query', 'fromType'])

//导出提示相关配置
const dialogInfo = ref({
  visible: false,
  title: '提示',
  btLoading: false,
  type: '',
  msg: '',
  width: '400px',
  flag: true,
  btList: [
    { label: '关闭', event: handleClose, show: true },
    {
      label: '打印',
      type: 'primary',
      event: checkConfirm,
      show: true,
    },
  ],
})
const page = ref({
  curPage: 1, // 当前页
  pageSize: 20, // 每页条数
})
// 过滤相关配置
const filterInfo = ref({
  sortArr: [],
  query: {
    sortString: '',
    copyQueryMap: {},
    groupMap: {},
    groups: [],
    queryMap: {},
    defaultQueryMap: {
      deliverProductType: {
        queryType: 'IN',
        value: 1,
      },
      supplierAuth: {
        asTbName: 'deliver_order',
        columnName: 'org_id',
        queryType: 'IN',
        queryCategory: 'AND',
        value: 'supplierAuth',
      },
    },
    queryParams: {},
    customizeUserVO: {},
  },
  searchList: [],
  searchBtn: [
    { type: 'button', label: '搜索', event: search },
    { type: 'button', label: '高级查询', event: advancedSearchShow },
    { type: 'button', label: '重置', event: clearSearch },
  ],
  btnList: [
    {
      value: 'excel',
      type: 'slot',
      show: proxy.$permission('pendDealDeliverOrder:exportExcel'),
    },
    {
      type: 'slot',
      value: 'print',
      show: proxy.$permission('pendDealDeliverOrder:print'),
    },
  ],
})
// 表格相关
const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  api: undefined,
  summaryFieldList: [
    { value: 'qty', formatter: proxy.$fn.qtyFormatter },
    { value: 'sumAmount', formatter: proxy.$fn.TripartiteMethod },
  ],
  data: [],
  selections: [],
  fieldList: [],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '120',
    btList: [
      {
        label: '收货',
        event: receiving,
        show: proxy.$permission('pendDealDeliverOrder:receiving'),
        ifRender: function (row) {
          return row.status === 2 || row.status === 3
        },
      },
      {
        label: '暂估收货',
        event: addEstimated,
        show: proxy.$permission('pendDealDeliverOrder:estimated'),
        ifRender: function (row) {
          return (
            (row.status === 2 || row.status === 3) &&
            row.isConsignBusiness == '0'
          )
        },
      },
    ],
  },
})
const detailInfo = ref({
  visible: false,
  id: '',
  type: '',
})
const purchOrderDetailInfo = ref({
  visible: false,
  orderId: ''
})
const detailListInfo = ref({
  visible: false,
})
const preferenceInfo = ref({
  visible: false,
})
const advancedSearchInfo = ref({
  visible: false,
  data: {},
})
const modifyDeliverInfo = ref({
  visible: false,
  title: '',
  orderId: '',
  deliverId: '',
  receiveAll: true,
  isEstimated: false,
})
const groupFlag = ref(false)
const clearType = ref(true)
const slipSelectRequest = ref(true)
const productionDateTime = ref([])
const validityDateTime = ref([])
const time = ref([])

const showDialog = computed({
  get() {
    return props.visible
  },
  set(newValue) {
    emits('update:visible', newValue) // 更新父组件visible
  },
})
const toPage = computed(() => {
  return proxy.$store.state.settings.toPage
})

let stopWatch = function () {}
onActivated(() => {
  stopWatch = watch(
    () => toPage.value,
    (val) => {
      if (val) {
        let menus = proxy.$store.state.permission.defaultMenus
        menus.forEach((item) => {
          if (item.children) {
            item.children.forEach((el) => {
              if (el.code === 'pendDealDeliverOrder' && el.url === val.url) {
                detailInfo.value.visible = false
                purchOrderDetailInfo.value.visible = false
                if (val.urlType === 1) {
                  getList()
                } else if (val.urlType === 2) {
                  proxy.$nextTick(() => {
                    detailInfo.value.id = val.businessId
                    detailInfo.value.visible = true
                    detailInfo.value.type = 'pendDealDeliverOrder'
                    sessionStorage.setItem('storeRowId', val.businessId)
                  })
                }
                proxy.$store.dispatch('settings/toPage', '')
              }
            })
          }
        })
      }
    },
    {
      deep: true,
      immediate: true,
    }
  )
})
onDeactivated(() => {
  stopWatch()
})

setData()
function setData() {
  let obj = {
    purchNo: {
      label: '采购单号',
      value: 'purchNo',
      componentType: 'input',
      type: 'slot',
      show: false,
      hidden: true,
    },
    price: {
      label: '单价',
      value: 'price',
      type: 'column',
      componentType: 'price',
      formatter: proxy.$fn.TripartiteMethod,
      permission: !proxy.$permission('pendDealDeliverOrder:price'),
      hidden: true,
    },
    sumAmount: {
      label: '总金额',
      value: 'sumAmount',
      formatter: proxy.$fn.TripartiteMethod,
      componentType: 'price',
      type: 'column',
      permission: !proxy.$permission('pendDealDeliverOrder:price'),
      hidden: true,
    },
    defaultSupplierPrice: {
      label: '默认供应商价格',
      value: 'defaultSupplierPrice',
      type: 'column',
      componentType: 'price',
      permission: !proxy.$permission('pendDealDeliverOrder:price'),
      formatter: proxy.$fn.TripartiteMethod,
      hidden: true,
      show: false,
    },
    statusValue: {
      label: '状态',
      value: 'statusValue',
      asValue: 'status',
      componentType: 'select-model',
      code: 'deliver_order_status',
      show: false,
      hidden: true,
    },
    supplierName: {
      label: '供应商',
      value: 'supplierName',
      asValue: 'orgId',
      componentType: 'slip-select',
      api: getSupplierAll,
      query: {
        supplierAuth: 'supplierId',
        sort: 'create_time desc',
      },
      clearable: true,
      filterable: true,
      keyField: 'supplierName',
      valueField: 'supplierId',
      show: false,
      hidden: true,
    },
  }
  tableInfo.value.fieldList = Object.values({
    ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
    ...proxy.$fn.deepClone(obj),
  })
  filterInfo.value.searchList = Object.values({
    ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
    ...proxy.$fn.deepClone(obj),
    commonName: {
      label: '通用名称',
      value: 'commonName',
      componentType: 'input',
      show: false,
      hidden: true,
    },
  })
  getCustomize()
}
function receiving(row) {
  //收货
  modifyDeliverInfo.value.deliverId = row.id
  modifyDeliverInfo.value.orderId = ''
  modifyDeliverInfo.value.visible = true
  modifyDeliverInfo.value.title = '根据发货单导入'
  modifyDeliverInfo.value.receiveAll = true
  modifyDeliverInfo.value.isEstimated = false
}
function addEstimated(row) {
  modifyDeliverInfo.value.deliverId = row.id
  modifyDeliverInfo.value.orderId = ''
  modifyDeliverInfo.value.visible = true
  modifyDeliverInfo.value.title = '根据发货单导入'
  modifyDeliverInfo.value.receiveAll = true
  modifyDeliverInfo.value.isEstimated = true
}
function handleClose() {
  dialogInfo.value.visible = false
}
function pageInfo(obj) {
  page.value = obj
}
//导出excel
async function exportExcel() {
  dialogInfo.value.visible = true
  dialogInfo.value.type = 'excel'
  dialogInfo.value.msg = '请选择数据导出范围'
  dialogInfo.value.btList[1].label = '导出'
  dialogInfo.value.flag = true
}
function checkConfirm() {
  if (dialogInfo.value.type === 'excel') {
    exportExcelList()
  } else if (dialogInfo.value.type === 'print') {
    printList()
  }
  dialogInfo.value.visible = false
  dialogInfo.value.msg = ''
}
function exportExcelList() {
  let query = {
    customizeDto: filterInfo.value.query,
  }
  let params = {
    ...query,
    ...page.value,
    page: dialogInfo.value.flag,
  }
  pendDealDeliverOrderExcelListDeliverOrder(params).then((resp) => {
    if (resp) {
      proxy.$fn.parseExcel(resp)
    }
  })
}
async function print() {
  //打印
  dialogInfo.value.visible = true
  dialogInfo.value.type = 'print'
  dialogInfo.value.msg = '请选择当数据打印范围'
  dialogInfo.value.btList[1].label = '打印'
  dialogInfo.value.flag = true
}
function printList() {
  fatchTemplateByCode({
    resourceCode: 'pendDealDeliverOrder:print',
    isDefault: 1,
  }).then((res) => {
    if (res && res.success) {
      let temp = proxy.$fn.getPrintTemp(res.data[0])
      getPrintData(temp, dialogInfo.value.flag)
    }
  })
}
function getPrintData(temp, flag) {
  let query = {
    customizeDto: filterInfo.value.query,
  }
  let params = {
    ...query,
    ...page.value,
    page: flag,
  }
  pendDealDeliverOrderPrintDetailDeliverOrder(params).then((res) => {
    if (res.success && res) {
      let data = proxy.$fn.deepClone(res.data)
      let newData = data.map((item) => {
        return {
          ...item,
          ...item.orderInfo,
        }
      })
      proxy.$lodop.preview(temp, newData)
    }
  })
}
function setPreferenceCallback(obj) {
  updateUserCustomize(obj.customizeUserVO).then((res) => {
    if (res && res.success) {
      getCustomize(!slipSelectRequest.value)
    }
  })
}
function advancedSearchShow() {
  advancedSearchInfo.value.visible = true
}
async function advancedSearchCallback(obj) {
  let _filterInfo = filterInfo.value
  let arr = [
    {
      fieldName: 'deptId',
      queryType: 'IN',
      queryCategory: 'AND',
      value: 'deptAuth',
    },
  ]
  _filterInfo.query.queryMap = {}
  _filterInfo.query.queryDtoList = [...obj.queryDtoList, ...arr]
  await getList()
  filterInfo.value.query.queryMap = proxy.$fn.deepClone(
    filterInfo.value.copyQueryMap
  )
  clearType.value = !clearType.value
}
// 获取列表
async function getList() {
  tableInfo.value.refresh = Math.random()
}
// 搜索
function search() {
  advancedSearchInfo.value.data = {}
  filterInfo.value.query.queryDtoList = []
  tableInfo.value.initCurpage = Math.random()
  tableInfo.value.refresh = Math.random()
}
function showDetail(row) {
  detailInfo.value.id = row.id
  detailInfo.value.visible = true
  detailInfo.value.type = 'pendDealDeliverOrder'
}
function showPurchDetail(row){
  let url = '/purch/order'
  let name = ''
  let routes = proxy.$store.state.permission.routes
  routes.map((item) => {
    if (item.children && item.children.length) {
      item.children.map((i) => {
        if (i.url === url) {
          name = url
        }
      })
    }
  })
  if (name) {
   purchOrderDetailInfo.value.visible = true
   purchOrderDetailInfo.value.orderId = row.purchId
  } else {
    proxy.$message({
      duration: 3500,
      type: 'warning',
      showClose: true,
      message: '你没有相应的菜单权限',
    })
  }
}
// 触发事件
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tableInfo.value.selections = [...data]
      break
  }
}
function clearSearch() {
  clearType.value = !clearType.value
  productionDateTime.value = []
  validityDateTime.value = []
  time.value = []
  advancedSearchInfo.value.data = {}
  filterInfo.value.query.queryMap = proxy.$fn.deepClone(
    filterInfo.value.copyQueryMap
  )
  search()
}
function getCustomize(_slipSelectRequest = true) {
  let _tableInfo = tableInfo.value
  let _filterInfo = filterInfo.value
  let param = {
    tableKey:
      'pendDealDeliverOrderList-com.slip.spd.entity.vo.supplier.DeliverOrderVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      filterInfo.value.query.customizeUserVO = data
      let searchInfo = proxy.$fn.setSearchList(
        _filterInfo.searchList,
        data.detail
      )
      console.log('searchInfo', proxy.$fn.deepClone(searchInfo))
      let tableFieldInfo = proxy.$fn.setFieldList(
        _tableInfo.fieldList,
        data.detail,
        true
      )
      let queryMap = {
        status: {
          queryType: 'IN',
          value: '2,3',
        },
      }
      _tableInfo.fieldList = tableFieldInfo.fieldList
      let searchDefaultValue = searchInfo.searchList.find(
        (item) => item.value === 'statusValue'
      ).searchDefaultValue
      _filterInfo.query.queryMap = {
        ..._filterInfo.defaultQueryMap,
        ...searchInfo.queryMap,
      }
      if (!searchDefaultValue) {
        _filterInfo.query.queryMap = {
          ..._filterInfo.query.queryMap,
          ...queryMap,
        }
      }
      filterInfo.value.copyQueryMap = proxy.$fn.deepClone(
        filterInfo.value.query.queryMap
      )
      if (props.fromType === 'route') {
        _filterInfo.query.queryMap = {
          ..._filterInfo.query.queryMap,
          ...props.query,
        }
      }
      _filterInfo.searchList = searchInfo.searchList
      _filterInfo.searchList.forEach((item) => {
        item.event = search
      })
      slipSelectRequest.value = _slipSelectRequest
      _tableInfo.api = getPendDealDeliverOrderCustomizeListPage
      getList()
    }
  })
}
function sortChange(column) {
  let _filterInfo = filterInfo.value
  if (_filterInfo.query.customizeUserVO.head.sortType === 0) {
    let arr = proxy.$fn.sortChange(column, _filterInfo.sortArr)
    _filterInfo.sortArr = arr
    _filterInfo.query.sortString = arr.toString()
    getList()
  }
}
function tableRowClassName(row) {
  if (row.row.nextGroups) {
    return 'bg-color-EBEEF5'
  } else {
    return ''
  }
}
function arraySpanMethod({ row, column, rowIndex, columnIndex }) {
  if (row.nextGroups) {
    if (columnIndex === 0) {
      // return {
      //   rowspan: 1,
      //   colspan: tableInfo.value.fieldList.length
      // };
      return [1, tableInfo.value.fieldList.length + 1]
    }
  }
}
function productionDateChange(val) {
  if (val && val.length) {
    filterInfo.value.query.queryMap.productionDate.value = val[0] + ',' + val[1]
  } else {
    filterInfo.value.query.queryMap.productionDate.value = null
  }
}
function validityDateChange(val) {
  if (val && val.length) {
    filterInfo.value.query.queryMap.validityDate.value = val[0] + ',' + val[1]
  } else {
    filterInfo.value.query.queryMap.validityDate.value = null
  }
}
</script>

<style scoped></style>
